<script setup>
import { ref, watch, onMounted, onUnmounted, toRefs } from 'vue'
import * as echarts from 'echarts'

// 接收 props
const props = defineProps({
  data: {
    type: Array,
    required: true
  }
})

const { data } = toRefs(props)

// 引用 DOM 容器
const chartRef = ref(null)
let chart = null

// 初始化图表函数
const initChart = () => {
  if (!chartRef.value) return

  // 销毁旧实例，避免多次初始化
  if (chart) {
    chart.dispose()
  }

  chart = echarts.init(chartRef.value)

  // 提取数据
  const departmentNames = data.value?.map((item) => item.name)
  const incomes = data.value?.map((item) => item.income)

  // 配置选项
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: departmentNames,
      axisLabel: {
        // rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '收入 (元)'
    },
    series: [
      {
        name: '收入',
        type: 'bar',
        data: incomes,
        barWidth: '50%',
        itemStyle: {
          color: '#73C9E6'
        }
      }
    ],
    grid: {
      left: '3%',
      right: '6%',
      bottom: '3%',
      containLabel: true
    }
  }

  // 渲染图表
  chart.setOption(option)
}

watch(
  () => data,
  () => {
    initChart()
  },
  { deep: true }
)

onMounted(() => {
  initChart()
  window.addEventListener('resize', () => {
    chart?.resize()
  })
})

// 在组件卸载时清理
onUnmounted(() => {
  if (chart) {
    chart.dispose()
  }
})
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 30rem"></div>
</template>
